package com.ustadzmenjawab.server;

import java.io.IOException;
import java.io.PrintWriter;
import java.util.LinkedList;
import java.util.List;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.json.JSONObject;

import com.ustadzmenjawab.shared.Constant;
import com.ustadzmenjawab.shared.SearchResult;

public class SearchSimilarDoc extends HttpServlet {
	@Override
	protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
		try {
			JSONObject responseObj = new JSONObject();
			List<JSONObject> docs = new LinkedList<JSONObject>();
			String keyword = req.getParameter("keyword");
			String deviceType = req.getParameter("device_type");
			String startStr = req.getParameter("start");
			String qidStr = req.getParameter("qid");
			int start = 0;
			if(startStr != null && startStr.length() > 0){
				start = Integer.parseInt(startStr);
			}
			int qid = 0;
			if(qidStr != null && qidStr.length() > 0){
				qid = Integer.parseInt(qidStr);
			}

			if(keyword != null && keyword.length() > 0 && qid > 0){
				DBAccess db = new LuceneAccess();
				List<SearchResult> ls = db.searchSimilarQuestion(keyword, qid, start, Constant.HIT_PER_PAGE);
				int searchCount = db.getCountSimilarResult(qid);
				for(SearchResult s : ls){
					JSONObject docObj = new JSONObject();
					docObj.put("id", s.getId());
					docObj.put("judul", s.getTitle());
					docObj.put("sumber", s.getSource());
					docObj.put("url", s.getUrl());
					docObj.put("summary",s.getSummary());
					docObj.put("ustadz", s.getUstadz());
					docObj.put("offline",s.getOffline());
					docs.add(docObj);
				}
				if(docs.size() > 0){
					responseObj.put("total_count", searchCount);
					responseObj.put("results", docs);
				}else{
					Object n = null;
					responseObj.put("total_count", 0);
					responseObj.put("results", n);
				}
			}
			PrintWriter writer = resp.getWriter();
			writer.write(responseObj.toString());
			writer.flush();
		}catch (Exception e) {  
			e.printStackTrace();
			//throw new ServletException(e);
		}
	}
}
